//
//  KitsViewController.m
//  QYer
//
//  Created by lanou on 16/8/6.
//  Copyright © 2016年 CaiZhuYu. All rights reserved.
//

#import "KitsViewController.h"
#import "KitsCityModel.h"

#import "CountrySectionViewCell.h"
#import "KitsCategoryCell.h"
#import "KitsCollectionCityCell.h"

@interface KitsViewController ()<UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate>

//左边
@property (nonatomic, strong) UITableView *categoryTableView;
@property (nonatomic, strong) NSMutableArray *categoryArray;

//右边
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableDictionary *dataDic;

@end

@implementation KitsViewController

- (NSMutableArray *)categoryArray {
    if (!_categoryArray) {
        _categoryArray = [NSMutableArray array];
    }
    return _categoryArray;
}

- (NSMutableDictionary *)dataDic {
    if (!_dataDic) {
        _dataDic = @{}.mutableCopy;
    }
    return _dataDic;
}


//左侧数据
- (void)getCategories {
    [NetWorkTool requstWithType:GET URLString:kitsCategory parameter:nil callBack:^(NSData *data, NSError *error) {
        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        for (NSDictionary *dic in jsonDic[@"data"]) {
            KitsCategoryModel *model = [[KitsCategoryModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.categoryArray addObject:model];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.categoryTableView reloadData];
            //默认选中第一行--最新
            [self.categoryTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionTop];
        });
        
    }];
}

- (void)createSubViews {
    
    
    //左边TableView
    self.categoryTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, 100, self.view.frame.size.height-64) style:UITableViewStylePlain];
    self.categoryTableView.delegate = self;
    self.categoryTableView.dataSource = self;
    self.categoryTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.categoryTableView];
    [self.categoryTableView registerNib:[UINib nibWithNibName:NSStringFromClass([KitsCategoryCell class]) bundle:nil] forCellReuseIdentifier:@"categoryReuse"];
    
    
    
    //右边CollectionView
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumLineSpacing = 10;
    //layout.minimumInteritemSpacing = 20;
    //layout.itemSize = CGSizeMake((kScreenWidth-120)/2, (kScreenWidth-130)*3/4);
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(100, 64, self.view.frame.size.width-100, self.view.frame.size.height-64) collectionViewLayout:layout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.collectionView];
    
    [self.collectionView registerNib:[UINib nibWithNibName:@"CountrySectionViewCell" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"CountryReuse"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"KitsCollectionCityCell" bundle:nil] forCellWithReuseIdentifier:@"CityReuse"];
    
}

//右侧数据
- (void)getKitsCollectionCityWithIDString:(NSString *)IDString {
    NSString *stringOne = @"http://open.qyer.com/qyer/guide/channel_list?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&id=";
    NSString *stringTwo = @"&oauth_token=81f78185dee6dc6040e10b8c43ad4b19&page=1&track_app_channel=App%2520Store&track_app_version=6.9.4&track_device_info=iPhone%25205%28ChinaMobile%2CChinaTelecom%2CChinaUnicom%29&track_deviceid=2D9E8D6C-2140-49DC-993D-D66133CC22C0&track_os=ios%25209.3.2&track_user_id=8252405&v=1";
    
    NSString *urlString = [NSString stringWithFormat:@"%@%@%@", stringOne, IDString, stringTwo];
    NSLog(@"网址是: %@", urlString);
    
    //字典移除上次数据
    [self.dataDic removeAllObjects];
    
    [NetWorkTool requstWithType:GET URLString:urlString parameter:nil callBack:^(NSData *data, NSError *error) {
        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSArray *jsonArray = jsonDic[@"data"];
        for (int i = 0; i < jsonArray.count; i++) {
            NSDictionary *dictionary = jsonArray[i];
            NSMutableArray *mArray = [NSMutableArray array];
            for (NSDictionary *dic in dictionary[@"guides"]) {
                KitsCityModel *model = [[KitsCityModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [mArray addObject:model];
            }
            [self.dataDic setObject:mArray forKey:dictionary[@"name"]];
        }
        //NSLog(@"%@", self.dataDic);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.collectionView reloadData];
        });
        
    }];
}

//测试
- (void)getKitsCollectionCityWithIDString {
    NSString *urlString = @"http://open.qyer.com/qyer/guide/channel_list?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&id=659&oauth_token=81f78185dee6dc6040e10b8c43ad4b19&page=1&track_app_channel=App%2520Store&track_app_version=6.9.4&track_device_info=iPhone%25205%28ChinaMobile%2CChinaTelecom%2CChinaUnicom%29&track_deviceid=2D9E8D6C-2140-49DC-993D-D66133CC22C0&track_os=ios%25209.3.2&track_user_id=8252405&v=1";
    [NetWorkTool requstWithType:GET URLString:urlString parameter:nil callBack:^(NSData *data, NSError *error) {
        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSArray *jsonArray = jsonDic[@"data"];
        for (int i = 0; i < jsonArray.count; i++) {
            NSDictionary *dictionary = jsonArray[i];
            NSMutableArray *mArray = [NSMutableArray array];
            for (NSDictionary *dic in dictionary[@"guides"]) {
                KitsCityModel *model = [[KitsCityModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [mArray addObject:model];
            }
            [self.dataDic setObject:mArray forKey:dictionary[@"name"]];
        }
        //NSLog(@"北美:%@", self.dataDic);
        
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.collectionView reloadData];
        });
        
    }];
}


#pragma mark -----

- (void)viewWillAppear:(BOOL)animated {
    [self getKitsCollectionCityWithIDString:@"999999"];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"看锦囊";
    
    // 设置inset
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    
    [self getCategories];
    
    [self createSubViews];
    
    //测试
    //[self getKitsCollectionCityWithIDString];
    
    
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


#pragma mark ----- UITableViewDataSource -----

//行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.categoryArray.count;
}

//行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

//Cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    KitsCategoryCell *cell = [tableView dequeueReusableCellWithIdentifier:@"categoryReuse" forIndexPath:indexPath];
    KitsCategoryModel *model = self.categoryArray[indexPath.row];
    cell.textLabel.text = model.cnname;
    cell.selectionStyle = UITableViewCellSeparatorStyleNone;
    return cell;
}

//点击Cell的方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    KitsCategoryModel *model = self.categoryArray[indexPath.row];
    NSString *IDString = model.ID.stringValue;
    //NSLog(@"%@", IDString);
    [self getKitsCollectionCityWithIDString:IDString];
}


#pragma mark ----- UICollectionViewDataSource -----

//分区数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return [self.dataDic.allKeys count];
}

//item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [self.dataDic[self.dataDic.allKeys[section]] count];
}

//item样式
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    KitsCollectionCityCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CityReuse" forIndexPath:indexPath];
    KitsCityModel *model = self.dataDic[self.dataDic.allKeys[indexPath.section]][indexPath.row];
    [cell.photoView sd_setImageWithURL:[NSURL URLWithString:model.cover] placeholderImage:[UIImage imageNamed:@"占位图"]];
    cell.cityNameLabel.text = model.guide_cnname;
    return cell;
    
}

//分区头标题
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    CountrySectionViewCell *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"CountryReuse" forIndexPath:indexPath];
    NSString *string = self.dataDic.allKeys[indexPath.section];
    view.countryNameLabel.text = string;
    return view;
}

//分区头尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeMake(kScreenWidth, 40);
}


//点击item的方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"%ld分区%ld个", indexPath.section, indexPath.row);
}

//设置collectionView当前页距离四周的边距
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(10, 10, 10, 10);
}

//item尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake((kScreenWidth - 160)/2, (kScreenWidth - 160)*3/4);
}









@end
